package net.huashitong.Project.web;

import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Project.entity.EarlyWarningNode;
import net.huashitong.Project.entity.NewProjects;
import net.huashitong.Project.service.EarlyWarningNodeService;
import net.huashitong.Project.service.NewProjectsService;
import net.huashitong.node.entity.NodeNewschedules;
import net.huashitong.node.service.NodeNewschedulesService;
import net.huashitong.user.entity.BnpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static net.huashitong.utils.UtilsTools.getClientIp;

@Controller
@RequestMapping(value = "/node/")
public class NodeInfoController extends JsonBaseController {
    @Override
    protected String getView(String s) {
        return null;
    }

    @Autowired
    private NewProjectsService newProjectsService;
    @Autowired
    private NodeNewschedulesService nss;
    @Autowired
    private EarlyWarningNodeService ewbs;

    @ResponseBody
    @RequestMapping(value = "getsmallnodeinfo", method = RequestMethod.GET)
    public Map<String, String> getSmallNodeById(String projectId, String nodeId) {
        NodeNewschedules schedules = nss.getNodeNewschedulesByProjectIdAndNodeId(projectId, nodeId);
        Map<String, String> scheduleMap = new HashMap<String, String>();
        scheduleMap.put("sysId", schedules.getSysId());
        scheduleMap.put("status", schedules.getStatus());
        if (StringUtils.isNotBlank(schedules.getPlanBeginDate())) {
            //计划开始时间
            scheduleMap.put("planBeginDate", schedules.getPlanBeginDate().replace(".", "-"));
        }
        if (StringUtils.isNotBlank(schedules.getFactFinishDate())) {
            //实际结束时间
            scheduleMap.put("factEndDate", schedules.getFactFinishDate().replace(".", "-"));
        }

        scheduleMap.put("planTime", schedules.getPlanTime());
        scheduleMap.put("factTime", schedules.getFactTime());
        scheduleMap.put("state", schedules.getState());
        return scheduleMap;
    }

    //修改时间节点信息
    @ResponseBody
    @RequestMapping(value = "editNodeTimeInfo", method = RequestMethod.POST)
    public Message editNodeTimeInfo(String sysId,
                                    String status,
                                    String planBeginDate,
                                    String factEndDate,
                                    String planTime,
                                    String factTime,
                                    String state,
                                    HttpServletRequest request) throws ParseException {
        String ip = getClientIp(request);
        BnpUser user = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        NodeNewschedules schedules = nss.getById(sysId);
        //小节点修改
        if ("2".equals(schedules.getType())) {
            if (ObjectUtils.isBlank(schedules)) {
                return coverMessage("500", "（内部出错）没有节点唯一标识");
            }

            if (StringUtils.isNotBlank(factEndDate) && StringUtils.isNotBlank(planBeginDate)) {
                Date factEndDate1 = sdf.parse(factEndDate);
                Date planBeginDate1 = sdf.parse(planBeginDate);
                long daysBetween = (planBeginDate1.getTime() - factEndDate1.getTime() + 1000000) / (3600 * 24 * 1000);
                if (daysBetween > 0) {
                    return coverMessage("500", "时间不合理");
                }
            }
            List<NodeNewschedules> list = nss.getNodeByProjectId(schedules.getProjectId());
            // 计划用时
            if (StringUtils.isNotBlank(planTime)) {
                schedules.setPlanTime(planTime);
            }
            // 节点状态
            schedules.setStatus(status);
            schedules.setState(state);
            // 开始时间(前端：实际开始时间，后端：计划开始日期)
            schedules.setPlanBeginDate(planBeginDate.replace("-", "."));
            // 实际结束时间
            schedules.setFactFinishDate(factEndDate.replace("-", "."));
            // 实际用时
            schedules.setFactTime(factTime);
            //获取未完成节点
            List<NodeNewschedules> noFinishNodes = nss.getNoFinishNode(schedules.getProjectId());
            //如果修改的节点是项目所有小节点中的最后一个未完成节点，那么当这个节点被修改成完成时，项目的状态也要改为完成
            if (noFinishNodes.size() == 1 && schedules.getNodeId().equals(noFinishNodes.get(0).getNodeId())) {
                if ("2".equals(status)) {
                    //更新项目状态
                    NewProjects project = newProjectsService.getById(schedules.getProjectId());
                    project.setStatus("4");//将项目状态设置为完成
                    newProjectsService.update(project, ip, user);
                } else if (!"2".equals(status)) {
                    //更新项目状态
                    NewProjects project = newProjectsService.getById(schedules.getProjectId());
                    project.setStatus("3");//将项目状态设置为项目进行中
                    newProjectsService.update(project, ip, user);
                }
            }
            if ("0".equals(status)) {
                schedules.setIsDelay("0");
            }
            //保存修改节点
            nss.saveOrUpdate(schedules);
            if ("0".equals(status) || "2".equals(status)) {
                EarlyWarningNode ewb = ewbs.queryEarlyWarningNodeByNodeSysId(sysId);
                if (ObjectUtils.isNotBlank(ewb)) {
                    ewbs.delete(ewb);
                }
            }

            int bigFactTime = 0;
            int bigPlanTime = 0;
            NodeNewschedules bigNode = new NodeNewschedules();
            for (NodeNewschedules nodeNewschedule : list) {

                if (schedules.getNodeId().equals(nodeNewschedule.getNodeId())) {
                    if ("2".equals(nodeNewschedule.getType()) && nodeNewschedule.getNodeId().split("\\.")[0].equals(schedules.getNodeIds())) {
                        bigFactTime += StringUtils.isNotBlank(schedules.getFactTime()) ? Integer.parseInt(schedules.getFactTime()) : 0;
                        bigPlanTime += StringUtils.isNotBlank(schedules.getPlanTime()) ? Integer.parseInt(schedules.getPlanTime()) : 0;
                    }
                } else {
                    if ("2".equals(nodeNewschedule.getType()) && nodeNewschedule.getNodeId().split("\\.")[0].equals(schedules.getNodeIds())) {
                        bigFactTime += StringUtils.isNotBlank(nodeNewschedule.getFactTime()) ? Integer.parseInt(nodeNewschedule.getFactTime()) : 0;
                        bigPlanTime += StringUtils.isNotBlank(nodeNewschedule.getPlanTime()) ? Integer.parseInt(nodeNewschedule.getPlanTime()) : 0;
                    }
                }

                if (nodeNewschedule.getNodeId().equals(schedules.getNodeId().split("\\.")[0])) {
                    bigNode = nodeNewschedule;
                }

            }
            bigNode.setPlanTime(bigPlanTime + "");
            bigNode.setFactTime(bigFactTime + "");
            nss.saveOrUpdate(bigNode);
        } else if ("1".equals(schedules.getType())) {
            if (ObjectUtils.isBlank(schedules)) {
                return coverMessage("500", "（内部出错）没有节点唯一标识");
            }
            if (StringUtils.isNotBlank(factEndDate) && StringUtils.isNotBlank(planBeginDate)) {
                Date factEndDate1 = sdf.parse(factEndDate);
                Date planBeginDate1 = sdf.parse(planBeginDate);
                long daysBetween = (planBeginDate1.getTime() - factEndDate1.getTime() + 1000000) / (3600 * 24 * 1000);
                if (daysBetween > 0) {
                    return coverMessage("500", "时间不合理");
                }
            }
            // 计划用时
            if (StringUtils.isNotBlank(planTime)) {
                schedules.setPlanTime(planTime);
            }
            // 节点状态
            schedules.setStatus(status);
            schedules.setState(state);
            // 开始时间(前端：实际开始时间，后端：计划开始日期)
            schedules.setPlanBeginDate(planBeginDate.replace("-", "."));
            // 实际结束时间
            schedules.setFactFinishDate(factEndDate.replace("-", "."));
            // 实际用时
            schedules.setFactTime(factTime);
            nss.update(schedules);
            if ("2".equals(state)) {
                List<NodeNewschedules> lists = nss.getNodeIdsList(schedules.getNodeId(), schedules.getProjectId(), "");
                for (NodeNewschedules nos : lists) {
                    nos.setState("2");
                    nss.update(nos);
                    EarlyWarningNode ewb = ewbs.queryEarlyWarningNodeByNodeSysId(nos.getSysId());
                    if (ObjectUtils.isNotBlank(ewb)) {
                        ewbs.delete(ewb);
                    }
                }
            }
            if ("1".equals(state)) {
                List<NodeNewschedules> lists = nss.getNodeIdsList(schedules.getNodeId(), schedules.getProjectId(), "");
                for (NodeNewschedules nos : lists) {
                    nos.setState("1");
                    nss.update(nos);
                }
            }
            List<NodeNewschedules> list = nss.getNodePlanTime(schedules.getProjectId(), "1");
            if (list.size() == 0) {
                NewProjects np = newProjectsService.getById(schedules.getProjectId());
                np.setStatus("1");
                newProjectsService.update(np);
            }
        }


        //小节点需不需要
        if ("1".equals(schedules.getState()) && "2".equals(schedules.getType())) {
            //大节点 nodeId
            String bigNodeId = schedules.getNodeIds();
            NodeNewschedules nodeNewschedule = nss.getNnsByProjectIdAndNodeId(schedules.getProjectId(), bigNodeId);
            nodeNewschedule.setState("1");
            nss.update(nodeNewschedule);
        }
        //小节点需不需要（小节点不需要）
        if ("2".equals(schedules.getState()) && "2".equals(schedules.getType())) {
            //大节点 nodeId
            String bigNodeId = schedules.getNodeIds();
            List<NodeNewschedules> nodeNewschedules = nss.getNodeIdsLists(bigNodeId, schedules.getProjectId());
            boolean flag = true;
            //大节点现在需要改成不需要
            for (NodeNewschedules n : nodeNewschedules) {
                if (schedules.getNodeId().equals(n.getNodeId())) {
                    continue;
                } else {
                    //其他节点不需要
                    if ("1".equals(n.getState())) {
                        flag = false;
                    }
                }
            }
            if (flag) {
                NodeNewschedules nodeNewschedule = nss.getNnsByProjectIdAndNodeId(schedules.getProjectId(), bigNodeId);
                nodeNewschedule.setState("2");
                nss.update(nodeNewschedule);
            }
        }


        return coverMessage("200", "修改成功");
    }
}
